<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.nameCn"
          clearable
          placeholder="分类中文名称"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model="query.nameEn"
          clearable
          placeholder="分类英文名称"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-select
          v-model="query.navStatus"
          placeholder="顯示狀態"
          clearable
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.numberTFStatus"
            :key="item.id"
            :label="item.dictValue"
            :value="item.dictKey"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="800px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" inline>
          <el-col :span="24">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="productCategory"
                style="width: 600px;"
                placeholder="选择上级分类"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="中文名称" prop="nameCn">
              <el-input v-model="form.nameCn" style="width: 220px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="nameEn">
              <el-input v-model="form.nameEn" style="width: 220px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示狀態">
              <el-radio-group v-model="form.navStatus">
                <el-radio
                  v-for="item in dict.sysShow"
                  :key="item.id"
                  :label="item.dictKey"
                >{{ item.dictValue }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类排序">
              <el-input-number
                v-model.number="form.sort"
                :min="0"
                :max="999999"
                controls-position="right"
                style="width: 220px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述">
              <el-input v-model="form.description" style="width: 220px;" />
            </el-form-item>
          </el-col>
          <el-col v-show="form.parentId" :span="12">
            <el-form-item label="包裝類型">
              <el-select v-model="form.packType" style="width: 220px;">
                <el-option
                  v-for="dict in dict.packType"
                  :key="dict.id"
                  :label="dict.dictValue"
                  :value="dict.dictKey"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-form-item label="图片" prop="icon">
            <el-upload
              ref="my-upload"
              :on-success="handleSuccess"
              :on-error="handleError"
              :headers="headers"
              :action="imagesUploadApi"
              :data="type"
              :show-file-list="false"
            >
              <img v-if="form.icon" :src="baseApi+form.icon" class="avatar" width="150px" height="150px">
              <el-button v-else size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <vxe-table
        :tree-config="{children: 'children'}"
        :expand-config="{lazy: true, loadMethod: loadContentMethod}"
        :data="crud.data"
        stripe
      >
        <vxe-table-column
          title="下级目录"
          type="expand"

          width="100px"
        >
          <template #content="{ row }">
            <div class="app-container">
              <vxe-table
                ref="xTable"
                :data="row.childData"
              >
                <vxe-table-column :show-overflow-tooltip="true" field="nameCn" title="二级分类"      >
                  <template slot-scope="scope">
                    <span>{{ scope.row.nameCn }}</span><br>
                    <span>{{ scope.row.nameEn }}</span>
                  </template>
                </vxe-table-column>
                <vxe-table-column field="icon" title="图片"      >
                  <template slot-scope="scope">
                    <img :src="baseApi + scope.row.icon" style="height: 50px" alt="">
                  </template>
                </vxe-table-column>
                <vxe-table-column field="sort" title="分类排序"       sortable />
                <vxe-table-column field="packType" title="包裝類型"      >
                  <template slot-scope="scope">
                    <span>{{ dict.label.packType[scope.row.packType] }}</span>
                  </template>
                </vxe-table-column>
                <vxe-table-column field="navStatus" title="显示狀態"      >
                  <template slot-scope="scope">
                    <span>{{ scope.row.navStatus === true ? '是' : '否' }}</span>
                  </template>
                </vxe-table-column>
                <vxe-table-column field="description" title="描述"       />
                <vxe-table-column
                  v-if="checkPer(['admin','productCategory:edit','productCategory:del'])"
                  title="操作"
                >
                  <template slot-scope="scope">
                    <el-button
                      v-permission="permission.edit"
                      :loading="crud.status.cu === 2"
                      size="mini"
                      type="primary"
                      icon="el-icon-edit"
                      @click="handleEdit(scope.$index, scope)"
                    />
                    <el-button
                      v-permission="permission.del"
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                    />
                  </template>
                </vxe-table-column>
              </vxe-table>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column :show-overflow-tooltip="true" field="nameCn" title="顶级分类"      >
          <template slot-scope="scope">
            <span>{{ scope.row.nameCn }}</span><br>
            <span>{{ scope.row.nameEn }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="icon" title="图片"      >
          <template slot-scope="scope">
            <img :src="baseApi + scope.row.icon" style="height: 50px" alt="">
          </template>
        </vxe-table-column>
        <vxe-table-column field="sort" title="分类排序"       sortable />
        <vxe-table-column field="navStatus" title="显示狀態"      >
          <template slot-scope="scope">
            <span>{{ scope.row.navStatus === true ? '是' : '否' }}</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="description" title="描述"       />
        <vxe-table-column
          v-if="checkPer(['admin','productCategory:edit','productCategory:del'])"
          title="操作"
          width="150px"

        >
          <template slot-scope="scope">
            <el-button
              v-permission="permission.edit"
              :loading="crud.status.cu === 2"
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope)"
            />
            <el-button
              v-permission="permission.del"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            />
          </template>
        </vxe-table-column>
      </vxe-table>
      <pagination />
    </div>
  </div>
</template>

<script>
import crudProductCategory from '@/api/pms/productCategory'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
// import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import VXETable from 'vxe-table'

VXETable.setup({
  expandConfig: {
    trigger: 'default',
    showIcon: true
  },
  icon: {
    TABLE_EXPAND_OPEN: 'vxe-icon--minus',
    TABLE_EXPAND_CLOSE: 'vxe-icon--plus'
  }
})

const defaultForm = {
  id: null,
  nameCn: null,
  nameEn: null,
  icon: null,
  sort: null,
  level: null,
  navStatus: true,
  parentId: 0,
  showStatus: true,
  description: null,
  categoryType: 0,
  packType: null
}
export default {
  name: 'ProductCategory',
  components: { pagination, crudOperation, rrOperation, Treeselect },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['sysShow', 'packType', 'numberTFStatus'],
  cruds() {
    return CRUD({
      title: '产品分类',
      url: 'productCategory/page',
      sort: ['sort:asc'],
      query: { parentId: 0, navStatus: 1 },
      crudMethod: { ...crudProductCategory },
      optShow: {
        add: true,
        edit: false,
        del: false,
        download: false,
        reset: true
      }
    })
  },
  data() {
    return {
      type: { type: 0 },
      tableData: [],
      childData: [],
      headers: {
        'Authorization': getToken()
      },
      productCategory: [],
      permission: {
        add: ['admin', 'productCategory:add'],
        edit: ['admin', 'productCategory:edit'],
        del: ['admin', 'productCategory:del']
      },
      rules: {
        nameCn: [
          { required: true, message: '分类中文名称不能为空', trigger: 'blur' }
        ],
        nameEn: [
          { required: true, message: '分类英文名称不能为空', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '图标不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'nameCn', display_name: '分类中文名称' },
        { key: 'nameEn', display_name: '分类英文名称' },
        { key: 'navStatus', display_name: '显示狀態' },
        { key: 'showStatus', display_name: '显示状态' }
      ]
    }
  },
  computed: {
    ...mapGetters(['imagesUploadApi', 'baseApi'])
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU]() {
      this.getTree()
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh](crud) {
      this.tableData = crud.data
      return true
    },
    loadContentMethod({ row }) {
      return new Promise(resolve => {
        setTimeout(() => {
          const params = { parentId: row.id }
          crudProductCategory.getProduct(params).then(res => {
            row.childData = res.data
            resolve()
          })
        }, 200)
      })
    },
    handleExceed() {
      this.$message.warning('当前限制选择 1张图片，请重新选择')
    },
    handleSuccess(res) {
      if (res.code === 0) {
        this.form.icon = res.data.url
      } else {
        this.$message.error('图片上传失败,请重新上传')
      }
    },
    handleError() {
      this.$message.error('图片上传失败,请重新上传')
    },

    getTree() {
      crudProductCategory.getTree({ categoryType: 0 }).then(res => {
        const children = res.data.map(function(obj) {
          if (!obj.leaf && !obj.children) {
            obj.children = null
          }
          return obj
        })
        this.productCategory = [{ id: 0, label: '顶级类目', children: children }]
      })
    },
    getProduct(tree, treeNode, resolve) {
      const params = { parentId: tree.id }
      setTimeout(() => {
        crudProductCategory.getProduct(params).then(res => {
          resolve(res.data)
        })
      }, 100)
    },
    sortChange(column) {
      if (column.order === 'ascending') {
        this.crud.sort = [column.prop + ':asc']
      }
      if (column.order === 'descending') {
        this.crud.sort = [column.prop + ':desc']
      }
      this.crud.refresh()
    },
    handleEdit(index, data) {
      this.crud.resetDataStatusNext(data.row)
      this.getTree()
      this.crud.toEdit(data.row)
    },
    handleDelete(data) {
      this.$confirm('此操作将刪除該分類,若有子分類也將一併刪除,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.resetDataStatusNext(data)
        this.crud.doDelete(data)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}

::v-deep .vue-treeselect__control, ::v-deep .vue-treeselect__placeholder, ::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
